<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            position: absolute;
            top: 200px;
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <button class="btn1">按下前进500</button>
    <button class="btn2">按下前进1000</button>
    <div class="box1"></div>
    <script>
        //封装动画
        function animate(obj, target, callback) {
            //先清除一次定时器
            clearInterval(obj.timer);
            obj.timer = setInterval(function () {
                //缓动动画公式   （目标距离 - 现在距离）/ 10
                // var step = (target - obj.offsetLeft) / 10;
                //js中要避免出现小数情况，需要取整
                // var step = Math.ceil((target - obj.offsetLeft) / 10);
                //可是，考虑到退回来出现负数的情况，取整情况有两种
                var step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil((target - obj.offsetLeft) / 10) : Math.floor((target - obj.offsetLeft) / 10);
                //判断动画停止条件
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer);
                    //回调函数写在定时器结束之后
                    //先判断有没有回调函数，如果有回调函数，则运行回调函数
                    if (callback) {
                        callback();
                    }
                }
                obj.style.left = obj.offsetLeft + step + 'px';
            }, 30)
        }

        var box1 = document.querySelector('.box1');
        var btn1 = document.querySelector('.btn1');
        var btn2 = document.querySelector('.btn2');

        //调用动画函数
        btn1.addEventListener('click', function () {
            animate(box1, 500);
        })
        btn2.addEventListener('click', function () {
            animate(box1, 1000, function () {
                box1.style.backgroundColor = 'red';
            });
        })
    </script>
</body>

</html>